# -*-coding:utf-8 -*-
import time
title = '''<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN">
  <head>
    <title>剑王朝</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <link href="stylesheet.css" rel="stylesheet" type="text/css"/>
  </head>
  <body>
'''
# h3 = '\n\t<h3 align="center">%s</h3>'
# paragraph = '\n\t<p>%s</p>'
openf = open('H:\\108601.txt','r',encoding='utf-8')
file = openf.readlines()
content = []
for i, lin in enumerate(file):
    time.sleep(0)
    line = lin.strip('\n')
    if '第' in line:
        if '章' in line:
            if len(line) < 40:
                one = '\n\t<h3 align="center">%s</h3>' %(line)
                content.append(one)
            else:
                par = '\n\t<p>%s</p>' %(line)
                content.append(par)
        else:
            par = '\n\t<p>%s</p>' %(line)
            content.append(par)
    else:
            par = '\n\t<p>%s</p>' %(line)
            content.append(par)
# html = open('H:\\108601.html','w',encoding='utf-8', errors='ignore')
# html.write(title)
# # html_content = ''''''
# for line in content:
#     # time.sleep(0)
#     # html_content = html_content + line
#     html.writelines(line)
# print('ok')
l_index = {}
for i, line in enumerate(file):
    time.sleep(0)
    if '第' in line:
        if '章' in line:
            if len(line) < 40:
                l_index[line] = i
lst_values = list(l_index.values())
with open('H:\\html\\Selection0.xhtml', 'w', encoding='utf-8', errors='ignore') as f:
    f.write(title)
    for line in content[:min(lst_values)]:
        f.writelines(line)
count = 0
while count < len(lst_values)-1:
    time.sleep(0.001)
    print(count+1, lst_values[count])
    chapter = content[lst_values[count]:lst_values[count+1]]
    path = 'H:\\html\\Selection' + str(count+1) + '.xhtml'
    with open(path, 'w', encoding='utf-8', errors='ignore') as f:
        f.write(title)
        for line in chapter:
            f.writelines(line)
    count = count + 1

with open('H:\\html\\Selection'+str(len(lst_values)+2)+'.xhtml', 'w', encoding='utf-8', errors='ignore') as f:
    f.write(title)
    for line in content[max(lst_values):]:
        f.writelines(line)